/*
 * Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
 */
package com.xinpan.exercise;

public class RemoveDuplicateFromSortedList2 {
    public ListNode deleteDuplicates(ListNode head) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(head == null)
            return null;
        ListNode newH = new ListNode(-1);
        newH.next = head;
        
        ListNode pre = newH;
        ListNode cur = head;
        
        while(cur != null)
        {
            boolean skip = false;
            ListNode next = cur.next;
            while(next != null && next.val == cur.val)
            {
                next = next.next;
                cur.next = next;
                skip = true;
            }
            if(skip)
            {
                pre.next = cur.next;
                cur = pre.next;
            }
            else
            {
                pre = cur;
                cur = cur.next;
            }     
        }
        return newH.next;
    }
}
